package com.ghxxzx.daglcustom.controller;

import com.ghxxzx.daglcustom.utils.ActivitiTools;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.tmsps.ne4spring.utils.wrapper.WrapMapper;
import org.tmsps.ne4spring.utils.wrapper.Wrapper;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ActivitDefineController {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private RepositoryService repositoryService;

	/**
	 * 查询流程定义列表
	 * 
	 * @return
	 */
	@RequestMapping("/activitDefineList")
	@ResponseBody
	public List<Map<String, Object>> activitDefineList(String name) {
		// 创建查询对象
		ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
		// 使用部署对象ID查询
		// processDefinitionQuery.deploymentId(deploymentId);
		// 使用流程定义ID查询
		// processDefinitionQuery.processDefinitionId(processDefinitionId)
		// 使用流程定义的KEY查询
		// processDefinitionQuery.processDefinitionKey(processDefinitionKey)

		// 使用流程定义的名称模糊查询
		if (name == null || "".equals(name.trim())) {
		} else {
			processDefinitionQuery.processDefinitionNameLike("%" + name + "%");
		}
		List<ProcessDefinition> list = processDefinitionQuery.list();
		return ActivitiTools.turnProcessDefinitions(list);
	}

	// 删除流程定义
	@GetMapping("/activiti_define_delete")
	@ResponseBody
	public Wrapper<String> activiti_define_delete(@Valid String deployment_id) {
		repositoryService.deleteDeployment(deployment_id);
		return WrapMapper.ok("删除成功");
	}

	// 启动一个流程实例
	@GetMapping("/activiti_define_start")
	@ResponseBody
	public Wrapper<String> activiti_define_start(@Valid String id) {
		ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().processDefinitionId(id).singleResult();

		Map<String, Object> varaiables = new HashMap<>();
		// ...此处可注入变量
		ProcessInstance pi = runtimeService.startProcessInstanceById(id, varaiables);
		runtimeService.setProcessInstanceName(pi.getId(), pd.getName());

		logger.info("启动流程实例,获取id-->{},实例名称-->{}", pi.getId(), pd.getName());
		return WrapMapper.ok(pi.getId());
	}

}
